package com.k.rabbitmq.amqp.demo;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

public class TestListener {
    private static final String EXCHANGE_NAME = "SMP_EXCHANGE_ALARM_TYPE_CHANGE";//"SMP_EXCHANGE_DATA_CHANGE";//"TEST_EXCHANGE_DATA";//"WBE_EXCHANGE_NOTICE_DATA";//"SMP_EXCHANGE_DATA_CHANGE";
    public static final String[] BINDING_KEY = new String[]{"DATA.CHANGE.GROUP","DATA.CHANGE.DEVICE"};//{"DATA.CHANGE.SPECIAL_SITUATION"};//new String[]{"DATA.CHANGE.DICT"};// new String[]{"DATA.CHANGE.DISTRICT","DATA.CHANGE.ORG","DATA.CHANGE.USER"};
    private static String getQueueName() {
        return "TEST_QUEUE_101";
    }
    private static void listener() throws Exception{
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("10.110.12.180");
        factory.setUsername("admin");
        factory.setPassword("Command_123");
        factory.setPort(27000);
        factory.setVirtualHost("mcc_vhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        // EXCHANGE 已经存在不需要声明
//        channel.exchangeDeclare(EXCHANGE_NAME, "topic",false,false,null);
        String queueName = getQueueName();//channel.queueDeclare().getQueue();
        // autoDelete:true 当监听队列不存在时会自动删除队列,测试时使用，正式时应为false下次可以继续消费未监听的消息
        channel.queueDeclare(queueName,true,false,true,null);
        for (String bindingKey : BINDING_KEY) {
            channel.queueBind(queueName, EXCHANGE_NAME, bindingKey);
        }
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [x] Received '" + delivery.getEnvelope().getRoutingKey() + "':'" + message + "'");
        };
        // https://www.cnblogs.com/piaolingzxh/p/5448927.html
        // autoAck：是否自动ack，如果不自动ack，需要使用channel.ack、channel.nack、channel.basicReject 进行消息应答
        channel.basicConsume(queueName, true, deliverCallback, consumerTag -> {
        });
    }
    public static void main(String[] args) {
        try {
            listener();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
